package com.gl.order.commom.util;

import cn.hutool.core.util.URLUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * @Author: liangSY
 * @Date: 2021/8/5 10:15
 * @ClassName: 导出word
 */
@Slf4j
public class WordUtils {

    private static Configuration configuration = null;

    private final static String templateFolder = "";

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_0);
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassicCompatible(true);
        //            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        configuration.setClassForTemplateLoading(WordUtils.class, "/templates");
    }

    /**
     * 导出word
     *
     * @param request
     * @param response
     * @param title    导出的文件名称
     */
    public static void export(HttpServletRequest request, HttpServletResponse response, Map<?, ?> map, String title, String templateName) {
        OutputStream out = null;
        File file = null;
        InputStream fin = null;
        try {
            Template freemarkerTemplate = configuration.getTemplate(templateName);
            // 调用工具类的createDoc方法生成Word文档
            file = createDoc(map, freemarkerTemplate);
            fin = new FileInputStream(file);

            // 设置浏览器以下载的方式处理该文件名
            String userAgent = request.getHeader("USER-AGENT");
            if (!StringUtils.contains(userAgent, "Mozilla")) {// 火狐浏览器
                title = URLUtil.encode(title, "UTF-8");
            }
            response.setContentType("application/msword");
            response.addHeader("Accept-Ranges", "bytes");
            response.addHeader("Content-Disposition", "attachment;filename=" + title + ".docx");

            out = response.getOutputStream();
            byte[] buffer = new byte[512];  // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                fin.close();
                file.delete();
            } catch (NullPointerException e) {
                throw new RuntimeException(e);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 创建word文档
     *
     * @param dataMap
     * @param template
     * @return
     */
    public static File createDoc(Map<?, ?> dataMap, Template template) {
        String name = System.currentTimeMillis() + ".docx";
        File f = new File(name);
        Template t = template;
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
//            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8"));
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }
        return f;
    }

}
